import { Component, Input, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { UtilsService } from '../../../../../../shared/services/utils.service';
import { OverviewModel } from '../../templates/overview/ratingOverview.model';
import { CompanyRiskRatingService } from '../../companyRiskRating.service';
import { HttpClient } from '@angular/common/http';
import { Subscription } from 'rxjs/Subscription';
import { ChartRiskFrameworkModel } from '../../templates/overview/models/chartRiskFramework.model';
import { ChartIssueExposureModel, ChartIssueExposureSummaryModel } from '../../templates/overview/models/chartIssueExposure.model';
import { ChartRiskManagementModel } from '../../templates/overview/models/chartRiskManagement.model';
import { ClusterService } from '../../../../riskCluster/cluster.service';

/**
 * MEI overview component
 *
 * Author: Sorin Spiru
 * Date: 16.01.2018
 */
@Component({
    selector: 'mei-rating-overview',
    templateUrl: '../../templates/overview/ratingOverview.component.html',
    styleUrls: [
        '../../../company.component.scss',
        '../../templates/overview/ratingOverview.component.scss'
    ],
    providers: [UtilsService],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class RatingOverviewMeiComponent extends OverviewModel {
    private sub: Subscription;
    private companySub: Subscription;
    private meiSub: Subscription;
    public company: any;
    public mei;

    @Input() set type(value: string) {
        this.meiType = value;
    }

    @Input() displayType = 'overview';

    public manageablePercent: string;

    constructor(
        private cdRef: ChangeDetectorRef,
        private route: ActivatedRoute,
        private riskService: CompanyRiskRatingService,
        private clusterService: ClusterService) {
        super(cdRef);
    }

    ngOnInit() {
        this.sub = this.route.params.subscribe(params => {
            this.load();
        });
    }

    ngOnDestroy() {
        this.sub.unsubscribe();
        if(this.companySub) this.companySub.unsubscribe();
        if(this.meiSub) this.meiSub.unsubscribe();
    }

    private load(): void {
        this.riskRating = undefined;
        this.cdRef.markForCheck();

        this.loaded = new Promise<void>((resolve, reject) => {
            //clusters
            this.clusterService.mei.subscribe(clusters => {
                if (clusters.length > 0) clusters[clusters.length - 1].topInterval = 20;
                this.riskClusters = clusters;
                this.companySub = this.riskService.company.subscribe(company => {
                    this.meiSub = this.riskService.mei.subscribe(mei => {
                        this.mei = mei;
                        this.currentClusterCode = mei.assessmentCode;

                        var cluster = this.riskClusters.filter(function (cluster) {
                            return cluster.code == mei.assessmentCode;
                        })[0];

                        this.currentClusterName = cluster != undefined ? cluster.name : "N/A";

                        //rating chart
                        this.riskRating = UtilsService.roundUp(mei.riskRating);

                        //risk framework chart
                        this.riskFramework = [
                            new ChartRiskFrameworkModel("Exposure", 0, mei.exposure, mei.exposure, "#B3D4D1"),
                            new ChartRiskFrameworkModel("Managed Risk", 0, mei.managedRisk, mei.managedRisk, "#A7A9AC"),
                            new ChartRiskFrameworkModel("Unmanaged Risk", mei.managedRisk, mei.exposure, mei.unmanagedRisk, "#000000")];

                        if (this.meiType !== "IdiosyncraticIssue") {
                            //issue exposure chart - for baseline, this is ignored
                            if (this.meiType == 'MaterialIssue') {
                                var relativeExposure = UtilsService.roundUp(mei.exposure - mei.subindustryExposureScore);
                                this.riskIssueExposure = [
                                    new ChartIssueExposureModel("Exposure", false, 'Subindustry Exposure', false, 0, mei.subindustryExposureScore, mei.subindustryExposureScore.toFixed(1), "#B3D5D1"),
                                    //has space because amchart uses this field as id for trendlines
                                    new ChartIssueExposureModel("Exposure ", false, company.companyName, true, 0, mei.exposure, mei.exposure.toFixed(1), "#B3D5D1"),
                                    //id purpose for amcharts
                                    new ChartIssueExposureModel("exposure", true, 'Relative Exposure - SubIndustry', false, mei.subindustryExposureScore, mei.exposure, relativeExposure > 0 ? "+" + relativeExposure : relativeExposure.toString(), "#68AAA3")
                                ];

                                this.riskIssueExposureSummary = [
                                    //new RiskIssueExposureSummaryModel("Relative Exposure - SubIndustry", relativeExposure > 0 ? "+" + relativeExposure : relativeExposure),
                                    new ChartIssueExposureSummaryModel("Excess Exposure - SubIndustry", ((mei.finalBetaFactor - 1) * 100).toFixed(0) + "%"),
                                    new ChartIssueExposureSummaryModel("Beta", mei.finalBetaFactor % 1 == 0 ? (mei.finalBetaFactor ? mei.finalBetaFactor.toString() : '') : mei.finalBetaFactor.toFixed(2))
                                ];
                            }

                            //management chart
                            this.manageablePercent = ((mei.manageableRisk * 100) / mei.exposure).toFixed(0) + "%";
                            this.riskManagement = [
                                new ChartRiskManagementModel("Exposure", mei.exposure, 100, "#B3D5D1", null, ''),
                                new ChartRiskManagementModel("Manageable Risk", mei.manageableRisk, Math.round((mei.manageableRisk * 100) / mei.exposure), "#B3D5D1", this.manageablePercent, ''),
                                new ChartRiskManagementModel("Managed Risk", mei.managedRisk, Math.round((mei.managedRisk * 100) / mei.exposure), "#A7A9AC", UtilsService.roundUp(mei.management) + '%', 'boldText')
                            ];
                        }
                        this.cdRef.markForCheck();
                        resolve();
                    }, error => this.errorCallback(_ => this.errorReset(), undefined));
                });
            });
        });
    }
}